<!--三包例外配件维护 厂端-->
<template>
  <div>
    <TopFilter :list="topFilterList" :cols="4" labelWidth="100" :collapse="true" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      :onSyncTableData="tableChange"
      :isExportExcel="true"
      exportFileName="三包例外配件维护.xlsx"
      :onCalcExportData="handleExportFun"
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      datakey="records"
      :isSelectColumn="false"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls" slot-scope="props">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandle">新增</el-button>

        <multiuse-button type="primary" icon="el-icon-download" class="btnStyle" :click="downloadHandle.bind(this)">下载模板 </multiuse-button>
        <UploadFile style="margin: 0 10px;" isOnlyButton :limit="20" type="primary" :fileTypes="['xls', 'xlsx']" icon="el-icon-upload" :actionUrl="actionUrl" @change="successHandler"
          >批量导入
        </UploadFile>
      </template>
    </FilterTable>

    <Drawer :visible.sync="visible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <add :formData="formData" @close="closeHandler" :handleType="handleType" />
    </Drawer>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import add from './add';
import { isEmpty } from '@/utils/utils';
import { exceptionPartRecord, updateStatus, delExceptionPart, downExceptPartTem } from '@/api/repair/threePacksOfManager/exceptionalPartsMaintenanceCDuan';
import { getAllUser } from '@/api/repair/batchEventManagement/activityDistribution';
import { arrayObjDeWeight } from '@/utils';
import { exportExcelFile } from '@/utils/index';
import { dealerMixin } from '@/pages/repair/batchEventManagement/dealerMixin';

export default {
  name: 'addItem',
  mixins: [dictionary, dealerMixin],
  data() {
    this.BaseTable = null;
    this.conf = { add: '新增', edit: '编辑', show: '显示' };
    return {
      topFilterList: this.createTopFilterList(),
      visible: false,
      fetchApi: exceptionPartRecord,
      dialogTitle: '',
      fetchParams: { xhrAbort: false },
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      threeId: '',
      actionUrl: '/api/dmscloud.activity/ttRpThreeInfo/uploadExceptPartTem'
    };
  },
  components: {
    add
  },

  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.initSelect();
  },
  methods: {
    tableChange(data) {
      // data.forEach((item, index) =>
      // {
      //   let status = item['status'] == '10041001' ? '启用' : '停用'
      //
      //   item.kybs = status
      // })
    },

    downloadHandle() {
      this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          downExceptPartTem()
            .then(res => {
              console.log(res, 'res');
              exportExcelFile(res.data, '三包例外配件维护模板');
            })
            .catch(err => {});
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },

    successHandler(e) {
      console.log('e:::', e);
      if (e != 1) {
        let obj = e[e.length - 1];
        let data = obj['url'];

        if (!isEmpty(data)) {
          this.$notify.error({ title: '提示信息', message: '导入失败数据的规则编号为:' + data });
        }
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },

    /*更新状态*/
    async updateStatusByRow(row, status) {
      //flag :zf法规与总成   zp 配件
      let res = await updateStatus({ id: row['partId'], status: status, flag: 'zp' });

      if (res.resultCode == 200 && res.success == true) {
        this.fetchParams = { ...this.fetchParams };

        this.$notify.success({ title: '提示信息', message: '操作成功' });
      } else {
        let errMsg = isEmpty(res.errMsg) ? '操作失败' : res.errMsg;

        this.$notify.error({ title: '提示信息', message: errMsg });
      }
    },

    async initSelect() {
      // let res = await getAllUser();
      // // 去重
      // let dataList = arrayObjDeWeight(res.data, 'userId');
      //
      // this.columns.find(item => item.dataIndex === 'createdBy').dictItems = dataList.map(x => ({
      //   text: x.employeeName,
      //   value: x.userId
      // }));
      //
      // this.columns.find(item => item.dataIndex === 'updatedBy').dictItems = dataList.map(x => ({
      //   text: x.employeeName,
      //   value: x.userId
      // }));

      this.getAllUsers(this.columns, ['createdBy', 'updatedBy'], 'table');
    },

    // 导出处理函数
    handleExportFun(row) {
      row.type = this.createDictText(row.type, 1023);
      // row.kybs = row['status'] == '10041001' ? '启用' : '停用'
    },

    addHandle() {
      this.formData = {};
      this.handleType = 'add';
      this.visible = true;
    },

    async delHandle(row) {
      let res = await delExceptionPart({ exceptionId: row['exceptionId'] });
      if (res.resultCode == 200 && res.success == true) {
        this.fetchParams = { ...this.fetchParams };
        this.$notify.success({ title: '提示信息', message: '操作成功' });
      } else {
        // let errMsg = isEmpty(res.errMsg) ? '操作失败' : res.errMsg;
        //
        // this.$notify.error({title: '提示信息', message: errMsg});
      }
    },

    detailHandle(row) {
      this.formData = row;
      this.handleType = 'show';
      this.showHandler();
    },

    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 150,
          render: props => {
            let obj = props.row;
            let status = obj['status'] == '10041001' ? true : false;
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
                  详情
                </el-button>
                <el-divider direction="vertical" />
                <multiuse-button type="text" size="mini" click={() => this.delHandle(props.row)}>
                  删除
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '可用标识',
          dataIndex: 'kybs',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input',
          initialValue: '启用'
        },
        {
          title: '配件代码',
          dataIndex: 'partNo',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '创建人',
          dataIndex: 'createdBy',
          sorter: true,
          dictItems: []
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '修改人',
          dataIndex: 'updatedBy',
          sorter: true,
          dictItems: []
        },
        {
          title: '修改时间',
          dataIndex: 'updatedAt',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'date-range'
        }
      ];
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo',
          placeholder: '配件代码...'
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName',
          placeholder: '配件名称...'
        }
      ];
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },

    changeHandle(val) {
      // val.bDate=moment(val['bDate']).format('YYYY-MM-DD')
      // val.eDate=moment(val['eDate']).format('YYYY-MM-DD')
      this.fetchParams = Object.assign({}, val);

      console.log(this.fetchParams);
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}三包例外配件维护`;

      this.visible = true;
    },

    closeHandler(type) {
      this.visible = false;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
